<script setup lang="ts">
import { Handle, Position, useVueFlow } from '@vue-flow/core'
import { computed, ref, watch, onMounted, onUnmounted } from 'vue'
import AddCustomKey from './AddCustomKey.vue';
const props = defineProps<{
  id: string;
  data: {
    name: string;
    custom_keys: Array<CustomKeyHandle>;
    role?:string;
    prompt?:string;
  };
  style?: Record<string, any>; // 添加 style 属性
}>()

const { updateNodeData, updateNode, updateNodeInternals } = useVueFlow()


const name = computed({
  get: () => props.data.name,
  set: (name) => updateNodeData(props.id, {...props.data, name: name }),
})

import useConnectionValid from './ts/connectionValid';
const { isValidConnection } = useConnectionValid();

// 节点属性
const role = ref(props.data.role);
const prompt = ref(props.data.prompt);
watch(() => [role.value, prompt.value], ()=>{
  updateNodeData(props.id, {...props.data, role: role.value, prompt: prompt.value})
})


// 定义自定义键的状态
import { type CustomKey, type CustomKeyHandle } from './ts/customKey'
const CustomKeys = ref<Array<CustomKey>>(props.data.custom_keys);
const customKeysHandle = ref<Array<CustomKeyHandle>>(props.data.custom_keys);
watch(() => CustomKeys.value, ()=>{
  customKeysHandle.value = CustomKeys.value.map((key, index) => {
    let value_type = 'msg';
    let class_type = 'AgentMsg';
    switch (key.type) {
      case 'bool':
        value_type = 'bool';
        break;
      case 'int':
        value_type = 'int';
        break;
      default:
        break;
    }
    return {
      type: key.type,
      name: key.name,
      value_type: value_type,
      id: `custom-key-${key.name}-${value_type}`,
      top: index * (30/CustomKeys.value.length) + 65,
      class_type:class_type,
      note: key.note,
    };
  });
  
  updateNodeData(props.id, {...props.data, custom_keys: customKeysHandle.value })
  updateNodeInternals(['1'])
},
{ deep: true })


// 监听节点容器大小变化
const AgentContentConainer = ref<HTMLElement | null>(null);
  let observer: ResizeObserver;
onMounted(() => {
  if (AgentContentConainer.value) {
    observer = new ResizeObserver(() => {
      if (!AgentContentConainer.value) return;
      const { width, height } = AgentContentConainer.value!.getBoundingClientRect();
      
      updateNode(props.id, {...props, style:{...props.style,height: props.style?.height}})
    });
    observer.observe(AgentContentConainer.value);  // 观察元素
  }
});
onUnmounted(()=>{
  if (AgentContentConainer.value) {
    observer.unobserve(AgentContentConainer.value);
  }
})  
defineOptions({
  name: 'AgentIfNode'
})
</script>

<template>
    <div class="AgentName"> <input :id="`${id}-input`" v-model="name"  class="nodrag"> </div>
    <div class="AgentContent" ref="AgentContentConainer">
      <Handle id="flow-in" type="target" :class="['AgentFlowInputHandle','top-0']" :position="Position.Left" title="FLow In"  :connectable="()=>{return isValidConnection(props.id,'flow-in', 'target')}" ><span class="HandleLeftSpan">Flow In</span></Handle>
      <Handle id="query-msg" type="target" :class="['AgentMsg','top-1']" :position="Position.Left" title="Query"   :connectable="()=>{return isValidConnection(props.id,'query-msg', 'target')}"><span class="HandleLeftSpan" >Query</span></Handle>
      <Handle id="context-msg" type="target" :class="['AgentMsg','top-2']" :position="Position.Left" title="Context"  :connectable="()=>{return isValidConnection(props.id,'context-msg', 'target')}"><span class="HandleLeftSpan" >Context</span></Handle>
      <Handle id="memory-msgs" type="target" :class="['AgentMsgs','top-3']" :position="Position.Left" title="Memory"  :connectable="()=>{return isValidConnection(props.id,'memory-msgs', 'target')}"><span class="HandleLeftSpan" >Memory</span></Handle>

      

      <Handle id="flow-true-next" type="source" :class="['AgentFlowOutputHandle','top-0']" :position="Position.Right"  :connectable="()=>{return isValidConnection(props.id,'flow-next','source')}" title="Flow Out True" ><span class="HandleRightSpan">True</span></Handle>
      <Handle id="flow-false-next" type="source" :class="['AgentFlowOutputHandle','top-1']" :position="Position.Right"  :connectable="()=>{return isValidConnection(props.id,'flow-next','source')}" title="Flow Out False" ><span class="HandleRightSpan">False</span></Handle>
      <Handle id="reason-msg" type="source" :class="['AgentMsg','top-2']" :position="Position.Right"  :connectable="()=>{return isValidConnection(props.id,'reason-msg','source')}" title="Reason" ><span class="HandleRightSpan">Reason</span></Handle>
      
      <div v-for="key in customKeysHandle" :key="key.id" class="custom-key-item">
        <Handle :id="key.id"  type="source" :class="key.class_type" :position="Position.Right" :connectable="()=>{return isValidConnection(props.id,key.id,'source')}" :style="{ top: `${key.top}%` }"><span class="HandleRightSpan">{{ key.name }}</span></Handle>
      </div>

      <div class="NodeData">
        <div class="input-row">
          <label for="roleInput">Role:</label>
          <input
            id="roleInput"
            type="text"
            v-model="role"
            placeholder="Enter role"
            :class="['text-input','nodrag']"
          />
        </div>

        <div class="input-row">
          <label for="promptInput">Prompt:</label>
          <textarea
            id="promptInput"
            v-model="prompt"
            placeholder="Enter prompt"
            :class="['text-input','nodrag']"
          ></textarea>
        </div>

        <AddCustomKey v-model="CustomKeys" ></AddCustomKey>
      </div>

    </div>

</template>


<style scoped>

.AgentName {
  position: relative;
  display: inline-block;
  font-size: 14px;
  width: 100%;
  padding-left: 70px;
  padding-right: 70px;
  text-align: center;
}

.AgentName input {
  max-height: 20px;
  height: 100%;
  width: 100%;
  border: none;
  outline: none;
  background: transparent;
  color: #333;
  font-size: 16px;
  padding: 8px 12px;
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
  text-align: center;
  background-color: #00000000;
}

/* 输入框聚焦时 */
.AgentName input:focus {
  background-color: #f5f5f5;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.5);
  color: #000;
}

/* 输入框没有内容时（placeholder显示） */
.AgentName input:placeholder-shown {
  color: #ffffff;
}

/* 输入框内容区域边距 */
.AgentName input::placeholder {
  color: #ccc;
  font-style: italic;
}

/* 输入框平滑过渡效果 */
.AgentName input {
  transition: background-color 0.3s, box-shadow 0.3s, color 0.3s;
}
.AgentContent{
  height: 100%;
  width: 100%;
}
</style>